import Vue from 'vue'
import store from "@/store";
import MD5 from './md5.js'
import {
    modal_color
} from './const.js'
import {ONLINEHOST} from "../config";
import lunar from "chinese-lunar";

// 时间戳转时间 now：当前时间  type:1 年月日时分秒  else
export const ZhDate = (time, type = 1) => {
    let now = new Date(time)
    let year = now.getFullYear()
    let month = now.getMonth() + 1
    let date = now.getDate()
    let hour = now.getHours()
    let minute = now.getMinutes()
    let second = now.getSeconds()
    if (type == 1) {
        return year + "-" + getzf(month) + "-" + getzf(date)
    } else if (type == 2) {
        return year + "-" + getzf(month) + "-" + getzf(date) + "  " + getzf(hour) + ":" + getzf(minute)
    } else if (type == 3) {
        return year + "-" + getzf(month) + "-" + getzf(date) + "  " + getzf(hour) + ":" + getzf(minute) + ":" +
            getzf(second)
    } else if (type == 4) {
        return year + "年" + getzf(month) + "月" + getzf(date) + "日"
    } else if (type == 5) {
        return date
    } else if (type == 6) {
        return year + "-" + getzf(month)
    } else if (type == 7) {
        return year
    } else if (type == 8) {
        return getzf(month) + "月" + getzf(date) + "日" + "  " + getzf(hour) + ":" + getzf(minute)
    } else if (type == 9) {
        return year + "." + getzf(month) + "." + getzf(date)
    } else if (type == 10) {
        return month
    }
}

// 时间戳转时间 now：当前时间  type:1 年月日时分秒  else
export const getYear = () => {
    let now = new Date()
    return now.getFullYear()
}


export const getzf = (num) => {
    if (parseInt(num) < 10) {
        num = '0' + num
    }
    return num
}

export const md5 = (str) => {
    return MD5(str).substr(8, 16).toUpperCase()
}


export const loading = (title = '加载中...', mask = false) => {
    uni.showLoading({
        title,
        mask
    })
}
export const loaded = () => {
    uni.hideLoading()
}

/*
 * 数据过滤全部
 * */
export const formatHtml = (str) => {
    const pattern = /<(\S*?)[^>]*>.*?|<.*? > /ig
    return str.replace(pattern, '').replace(/&nbsp;/ig, "")
}

/**
 * 给html添加指定样式 常用于rich text的子节点
 * @param {*} html 需要处理的html文本
 * @param {*} rule {
            img: {
                "max-width": "100%"
            }
        }   增加的样式规则 {元素名称:{css名称:属性}}
 */
export const htmlBeautify = (html, rule) => {
    if (!rule) {
        rule = {
            img: {
                "max-width": "100%"
            }
        }
    }
    for (const key in rule) {
        if (rule.hasOwnProperty(key)) {
            const element = rule[key];
            let style = ';'
            for (const k in element) {
                if (element.hasOwnProperty(k)) {
                    const v = element[k];
                    style += `${k}:${v};`
                }
            }
            // let reg = new RegExp(`<${key}>`, 'g')
            var reg = new RegExp(`(i?)(\<${key})(?!(.*?style=[\'\"](.*)[\'\"])[^\>]+\>)`, "gmi");
            let reg1 = new RegExp(`<${key}(.*?)style=[\'\"](.*?)[\'\"]`, 'gmi')

            html = html.replace(reg, `$2 style="" $3`).replace(reg1, `<${key} $1 style="$2${style}"`)
        }
    }
    return html
}


/**
 * 数据过滤全部
 * @param {*} state
 * @param {*} arr
 * @returns
 */
export const optionList = (state, arr) => {
    if (state) {
        return arr
    } else {
        return arr.slice(1)
    }
}

/**
 * value转换为label
 * @param {*} val
 * @param {*} arr
 * @returns
 */
export const filesCN = (val, arr) => {
    let _str = arr.filter(item => val === item.value)
    return _str[0].label
}

export const confirm = (title, msg, fn, confirmButtonText = '确认', showCancelButton = false, cancel = () => {
                        },
                        cancelButtonText = '取消') => {
    uni.showModal({
        title: title,
        content: msg,
        confirmText: confirmButtonText,
        cancelText: cancelButtonText,
        confirmColor: modal_color,
        showCancel: showCancelButton,
        success(res) {
            if (res.confirm) {
                fn()
            } else {
                cancel()
            }
        },
        fail(e) {
            console.log(e)
        }
    })
}

export const toPage = (page, replace = 0, events = {}) => {
    if (replace === 0) {
        uni.navigateTo({
            url: page
        })
    }

    if (replace === 1) {
        uni.redirectTo({
            url: page
        })
    }
    if (replace === 2) {
        uni.redirectTo({
            url: page
        })
    }
    if (replace === 3) {
        uni.switchTab({
            url: page
        })
    }
}

export const toLogin = () => {
    uni.navigateTo({
        url: '/pages/login/login',
        success() {
            toast('请先登录')
        }
    })
}

export const onShareAppMessage = (path = '') => {
    let _routes = getCurrentPages()
    let _route = _routes[_routes.length - 1].$page.fullPath
    return {
        path: `${path || _route}&spread_uid=${store.state.user.id}`
    }
}

export const onShareTimeline = (name = '') => {
    return {
        title: name,
        query: `spread_uid=${store.state.user.id}`,
    }
}

export const toast = (title, icon = 'none', duration = 2000) => {
    uni.showToast({
        title,
        icon,
        duration,
    })
}

export const toastEnd = () => {
    uni.hideToast()
}

export const loginTimeOut = () => {
    toast('登录状态已过期，请您重新登录')
    store.dispatch('LogOut').then(() => {
        uni.redirectTo({
            url: '/pages/index/index'
        })
    })
}

export const userLogout = () => {
    confirm('退出登录', '你确定退出当前帐号吗？', logout, '退出', true)
}

export const logout = () => {
    store.dispatch('LogOut').then(() => {
        uni.reLaunch({
            url: '/pages/index/index'
        })
    })
}
export const groupByCount = (arr, count) => {
    const result = [];
    let temp = [];

    for (let i = 0; i < arr.length; i++) {
        temp.push(arr[i]);
        if (temp.length === count) {
            result.push(temp);
            temp = [];
        }
    }

    if (temp.length > 0) {
        result.push(temp);
    }

    return result;
}


export const openFile = (url, name) => {
    if (isImageType(url)) {
        uni.previewImage({
            urls: [url],
            fail: (e) => {
                console.log(e)
            }
        })
    } else {
        uni.downloadFile({
            url: url,
            success: function (res) {
                var filePath = res.tempFilePath;
                uni.openDocument({
                    filePath: filePath
                })
            }
        });

    }
}

export const downFile = (url, fn = () => {
}) => {
    if (isImageType(url)) {
        uni.downloadFile({
            url: url,
            success: function (res) {
                var filePath = res.tempFilePath;
                uni.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success: function () {
                        toast('保存成功')
                        fn()
                    },
                    fail(e) {
                        console.log(e)
                    }
                });
            }
        });
    } else {
        uni.downloadFile({
            url: url,
            success: function (res) {
                var filePath = res.tempFilePath;
                uni.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success: function () {
                        fn()
                        toast('保存成功')
                    }
                });
            }
        });
    }
}


export const isImageType = (name) => {
    let _name = name.split('?')
    _name = _name[0].split('.')
    if (!_name.length) return false
    // toLowerCase() 将字符串转换为小写，返回一个新的字符串
    return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(_name[_name.length - 1]
        .toLowerCase()) !== -1
}

export const isArray = (value) => {
    return Object.prototype.toString.call(value) === '[object Array]'
}


export const wxOauth2Url = () => {
    return `https://open.weixin.qq.com/connect/qrconnect?appid=wx8694c2c9ad409b40&redirect_uri=${decodeURIComponent(location.href)}&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect`
    // return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8694c2c9ad409b40&redirect_uri=http://hygl.zhichenghui.org.cn/member/user/wchat&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
}

export const getUrlParams = (url) => {
    // 截取url中的code方法
    var theRequest = new Object();
    if (url.indexOf('?') != -1) {
        var str = url.substr(url.indexOf('?') + 1);
        var strs = str.split('&');
        for (var i = 0; i < strs.length; i++) {
            var items = strs[i].split('=');
            theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
        }
    }
    return theRequest;
}


export const toChinesNum = (num) => {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
    let unit = ['', '十', '百', '千', '万']
    num = parseInt(num)
    let getWan = (temp) => {
        let strArr = temp.toString().split('').reverse()
        let newNum = ''
        let newArr = []
        strArr.forEach((item, index) => {
            newArr.unshift(item === '0' ? changeNum[item] : changeNum[item] + unit[index])
        })
        let numArr = []
        newArr.forEach((m, n) => {
            if (m !== '零') numArr.push(n)
        })
        if (newArr.length > 1) {
            newArr.forEach((m, n) => {
                if (newArr[newArr.length - 1] === '零') {
                    if (n <= numArr[numArr.length - 1]) {
                        newNum += m
                    }
                } else {
                    newNum += m
                }
            })
        } else {
            newNum = newArr[0]
        }

        return newNum
    }
    let overWan = Math.floor(num / 10000)
    let noWan = num % 10000
    if (noWan.toString().length < 4) {
        noWan = '0' + noWan
    }
    return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}

const _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789';

/**
 * 随机生成索引
 * @param min 最小值
 * @param max 最大值
 * @param i 当前获取位置
 */
const RandomIndex = (min, max, i) => {
    let index = Math.floor(Math.random() * (max - min + 1) + min),
        numStart = _charStr.length - 10;
    //如果字符串第一位是数字，则递归重新获取
    if (i == 0 && index >= numStart) {
        index = RandomIndex(min, max, i);
    }
    //返回最终索引值
    return index;
}

/**
 * 随机生成字符串
 * @param len 指定生成字符串长度
 */
export const getRandomString = (len) => {
    let min = 0, max = _charStr.length - 1, _str = '';
    //判断是否指定长度，否则默认长度为15
    len = len || 15;
    //循环生成字符串
    for (var i = 0, index; i < len; i++) {
        index = RandomIndex(min, max, i);
        _str += _charStr[index];
    }
    return _str;

}

export const lengthScaleZh = (val) => {
    let num = Number(val.toFixed(1))
    if (num === 20) return 2
    if (num === 19) return 1.9
    if (num === 18) return 1.8
    if (num === 17) return 1.7
    if (num === 16) return 1.6
    if (num === 15) return 1.5
    if (num === 14) return 1.4
    if (num === 13) return 1.3
    if (num === 12) return 1.2
    if (num === 11) return 1.1
    if (num === 10) return 1
    if (num === 9) return 0.1
    if (num === 8) return 0.2
    if (num === 7) return 0.3
    if (num === 6) return 0.4
    if (num === 5) return 0.5
    if (num === 4) return 0.8
    if (num === 3) return 0.7
    if (num === 2) return 0.8
    if (num === 1) return 0.9
    if (num === 0) return 0
}


export const lengthScaleZhShow = (num) => {
    // let num = Number(val.toFixed(1))
    if (num === 20) return 2
    if (num === 19) return 1.9
    if (num === 18) return 1.8
    if (num === 17) return 1.7
    if (num === 16) return 1.6
    if (num === 15) return 1.5
    if (num === 14) return 1.4
    if (num === 13) return 1.3
    if (num === 12) return 1.2
    if (num === 11) return 1.1
    if (num === 10) return 1
    if (num === 9) return 1.1
    if (num === 8) return 1.2
    if (num === 7) return 1.3
    if (num === 6) return 1.4
    if (num === 5) return 1.5
    if (num === 4) return 1.8
    if (num === 3) return 1.7
    if (num === 2) return 1.8
    if (num === 1) return 1.9
    if (num === 0) return 2
}


export const lengthScaleBack = (val) => {
    if (val === undefined) return 14
    let num = Number(val.toFixed(1))
    if (num === 2) return 20
    if (num === 1.9) return 19
    if (num === 1.8) return 18
    if (num === 1.7) return 17
    if (num === 1.6) return 16
    if (num === 1.5) return 15
    if (num === 1.4) return 14
    if (num === 1.3) return 13
    if (num === 1.2) return 12
    if (num === 1.1) return 11
    if (num === 1) return 10
    if (num === 0.1) return 9
    if (num === 0.2) return 8
    if (num === 0.3) return 7
    if (num === 0.4) return 6
    if (num === 0.5) return 5
    if (num === 0.6) return 4
    if (num === 0.7) return 3
    if (num === 0.8) return 2
    if (num === 0.9) return 1
    if (num === 0) return 0
}

export const formatRichText = (html) => {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
        match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
        match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
        match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
        return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
        match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
        return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
    return newContent;
}


export const downImg = (src) => {
    // #ifdef H5
    return window.location.href = ONLINEHOST + '/novel/download.action?url=' + src
    // #endif
    loading('保存中...')
    uni.downloadFile({
        url: src,
        success: (res) => {
            if (res.statusCode === 200) {
                saveImg(res.tempFilePath)
            }
        },
        fail: (res) => {
            this.closePopup()
            console.log("下载失败", res.errMsg);
        }
    })
}

export const saveImg = (url) => {

    uni.getSetting({
        success(res) {
            loaded()
            if (!res.authSetting['scope.writePhotosAlbum']) {
                uni.authorize({ //调用用户信息授权弹框
                    scope: 'scope.writePhotosAlbum',
                    success() { // 用户允许授权用户信息
                        uni.saveImageToPhotosAlbum({
                            filePath: url,
                            success(res) {
                                loaded()
                                toast('已保存至相册', 'success')
                            },
                            fail(res) {
                                toast('保存失败1')
                            },
                        });
                    },
                    fail() {
                        uni.showModal({
                            title: '提示',
                            content: '您已经拒绝使用相册授权',
                            confirmText: '去设置',
                            success(res) {
                                if (res.confirm) {
                                    uni.openSetting({
                                        success() {
                                            console.log('成功打开设置');
                                        },
                                        fail() {
                                            console.log('打开设置失败');
                                        }
                                    })
                                } else if (res.cancel) {
                                    console.log('用户点击取消');
                                }
                            }
                        })
                    }
                });
            } else {
                uni.saveImageToPhotosAlbum({
                    filePath: url,
                    success(res) {
                        loaded()
                        toast('已保存至相册', 'success')
                    },
                    fail(res) {
                        toast('保存失败2')
                    },
                });
            }
        }
    })
}


export const getDate = (day) => {
    var today = new Date()
    // 获取时间戳(毫秒级)
    /*
      day为1，则是，明天的时间戳
      day为0，则是，今天的时间戳
      day为-1，则是，昨天的时间戳
      day为-2，则是，前天的时间戳
    */
    var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day
    // Date.setTime(时间戳)：设置当前日期的时间
    today.setTime(targetday_milliseconds)
    var tYear = today.getFullYear() // 年
    var tMonth = today.getMonth() // 月
    var tDate = today.getDate() // 日
    tMonth = doHandleMonth(tMonth + 1)
    tDate = doHandleMonth(tDate)

    return tYear + '-' + tMonth + '-' + tDate
}
export const doHandleMonth = (month) => {
    var m = month
    if (month.toString().length === 1) {
        m = '0' + month
    }
    return m
}


export const zhString = (val) => {
    let str = val.replace(/\r\n/g, "\n")
    str = str.replace(/\r/g, "\n")
    let createText = str.split('\n')
    let _arr = []
    createText.map(item => {
        if (item.trim()) _arr.push(item)
    })
    return _arr.join('&')
}
export const zhArr = (val) => {
    let str = val.replace(/\r\n/g, "\n")
    str = str.replace(/\r/g, "\n")
    let createText = str.split('\n')
    let _arr = []
    createText.map(item => {
        if (item.trim()) _arr.push(item)
    })
    return _arr
}


export const isWechat = () => {

    var ua = window.navigator.userAgent.toLowerCase();

    if (ua.match(/micromessenger/i) == 'micromessenger') {

        // console.log('是微信客户端')

        return true;

    } else {

        // console.log('不是微信客户端')

        return false;

    }

}


export const conversionText = (num) => {
    let _text = Number(num) >= 0 ? '减' : '增'
    return _text

}

export const conversionNum = (num,fixed=1) => {
    let _num = Number(num) < 0 ? -Number(num) : Number(num) === 0 ? 0 : Number(num)
    return _num.toFixed(fixed)

}

export const conversionUnit = (num) => {
    let _unit = Number(num) < 0 ? '-' : Number(num) === 0 ? '' : '+'
    return _unit

}

// 公历转农历
export const solarToLunar = (data) => {
    return lunar.solarToLunar(new Date(data));
};

// 农历转公历
export const lunarToSolar = (year, month, day) => {
    return lunar.lunarToSolar(year, month, day);
};